import Vue from 'vue'
import axios from 'axios'
// import VueAxios from 'vue-axios'
import VueCookie from 'vue-cookie'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import App from './App'
import router from './router'
import store from './store'
import storage from './storage/index'

import Print from 'vue-print-nb'


Vue.use(Print); 

Vue.use(ElementUI);
//Vue.use(VueAxios,axios);
Vue.use(VueCookie);

if (!process.env.IS_WEB) Vue.use(require('vue-electron'))
Vue.http = Vue.prototype.$http = axios
Vue.config.productionTip = false

Vue.prototype.resetSetItem = function (key, newVal) {
  if (key === 'user') {
      // 创建一个StorageEvent事件
      var newStorageEvent = document.createEvent('StorageEvent');
      const storage = {
          setItem: function (k, val) {
              sessionStorage.setItem(k, val);

              // 初始化创建的事件
              newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);

              // 派发对象
              window.dispatchEvent(newStorageEvent)
          }
      }
      return storage.setItem(key, newVal);
  }
}












    axios.defaults.baseURL = 'http://app.yejianping.cn/api';//设置路由访问
    axios.defaults.timeout = 30000;//设置超时时间

    // 请求拦截器
    axios.interceptors.request.use(
        config => {
            //console.log(config);
            if (localStorage.getItem("x_csrf_token")) {
              config.headers.x_csrf_token = localStorage.getItem("x_csrf_token");
            }
            if (localStorage.getItem("access_token")){
              config.headers.Authorization = 'Bearer ' + localStorage.getItem("access_token")
            }
            return config;
            
        },
        function(err) {
            console.log("失败信息" + err);
        }
    );


/* 响应拦截器 */
 
axios.interceptors.response.use(function (response) { // ①10010 token过期（30天） ②10011 token无效

if (response.data.status === 402 || response.data.status === 10011) {

 
    storage.localRemove('access_token') // 删除已经失效或过期的token（不删除也可以，因为登录后覆盖）
 
    router.replace({
 
        path: '/home' // 到登录页重新获取token
 
    })

    Vue.prototype.$message.error('登录已过期，请重新登录!')
 
} else if (response.data.access_token) { // 判断token是否存在，如果存在说明需要更新token
 
    storage.localSet('access_token', response.data.access_token) // 覆盖原来的token(默认一天刷新一次)
 
}
 
    return response
 
}, function (error) {
 
    return Promise.reject(error)
 
});
 












/* eslint-disable no-new */
new Vue({
  components: { App },
  router,
  store,
  template: '<App/>'
}).$mount('#app')


